<script setup lang="ts">
import { Add } from '@vicons/ionicons5'
import { useUserStore } from '@/stores'
import { imageUrlToFile } from '@/hooks/imageUrlToFile'
import type { FormRules, UploadFileInfo } from 'naive-ui'
import { userUpdateUserService } from '@/api/user'
import { type Ref } from 'vue'
import { ref, onMounted } from 'vue'

const userStore = useUserStore()

// 表单数据
type FormModel = {
  id: number
  username: string
  password: string
  nickname: string
  email: string
  gender: number
  avatar: File | null
  desc: string
  isAdmin: boolean
  [key: string]: any
}

//预览图片地址,表单里面是文件不好展示，所以这里用图片地址
const imgUrl = ref('')

//表单数据
const formModel: Ref<FormModel> = ref({
  id: 0,
  username: '',
  password: '',
  nickname: '',
  email: '',
  gender: 0,
  avatar: null,
  desc: '',
  isAdmin: false
})

// 上传前的钩子函数限制只能上传一张图片，这里用数组存储
const fileList: Ref<Array<File>> = ref([])
const beforeUpload = (file: File) => {
  console.log(1)
  fileList.value = [] // 清空 fileList
  fileList.value.push(file)
  return true
}
// 上传图片预览
const handleImgChange = (fileList: UploadFileInfo[]) => {
  console.log(fileList)
  const file = fileList[0].file as File
  //更新表单数据,表单数据并没有upload绑定，所以这里需要手动更新
  formModel.value.avatar = file
  // 本地预览
  imgUrl.value = URL.createObjectURL(file)
}

//默认表单数据
onMounted(async () => {
  imgUrl.value = userStore.userInfo.avatar
  if (userStore.userInfo.avatar) {
    const avatar = await imageUrlToFile(userStore.userInfo.avatar, 'avatar.jpg')
    formModel.value.avatar = avatar
  }
  formModel.value.id = userStore.userInfo.id
  formModel.value.username = userStore.userInfo.username
  formModel.value.password = userStore.userInfo.password
  formModel.value.nickname = userStore.userInfo.nickname
  formModel.value.email = userStore.userInfo.email
  formModel.value.gender = userStore.userInfo.gender
  formModel.value.desc = userStore.userInfo.desc
  formModel.value.isAdmin = userStore.userInfo.isAdmin
})
//校验规则
const formRef = ref()
const rules: FormRules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少6位', trigger: 'blur' }
  ],
  nickname: [{ required: true, message: '请输入昵称', trigger: 'blur' }],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱', trigger: 'blur' }
  ],
  gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
  desc: [],
  isAdmin: [{ required: true, message: '请选择权限', trigger: 'change' }]
}
const onSubmit = async () => {
  await formRef.value?.validate()
  console.log(formModel.value)
  const formData = new FormData()
  for (let key in formModel.value) {
    formData.append(key, formModel.value[key])
  }
  console.log(formData.get('avatar'))
  const res = await userUpdateUserService(formData)
  //更新用户信息
  userStore.setUserInfo(res.data.data)
  //更新表单
  let avatar = null
  if (res.data.data.avatar) {
    avatar = await imageUrlToFile(res.data.data.avatar, 'avatar.jpg')
    imgUrl.value = res.data.data.avatar
  }
  formModel.value = {
    id: res.data.data.id,
    username: res.data.data.username,
    password: res.data.data.password,
    nickname: res.data.data.nickname,
    email: res.data.data.email,
    gender: res.data.data.gender,
    avatar: avatar,
    desc: res.data.data.desc,
    isAdmin: res.data.data.isAdmin
  }
}
</script>

<template>
  <NCard>
    <n-form :rules="rules" :model="formModel" ref="formRef">
      <n-form-item label="用户名" path="username">
        <n-input v-model:value="formModel.username" placeholder="请输入用户名" disabled />
      </n-form-item>
      <n-form-item label="密码" path="password">
        <n-input v-model:value="formModel.password" placeholder="请输入密码" />
      </n-form-item>
      <n-form-item label="昵称" path="nickname">
        <n-input v-model:value="formModel.nickname" placeholder="请输入昵称" />
      </n-form-item>
      <n-form-item label="邮箱" path="email">
        <n-input v-model:value="formModel.email" placeholder="请输入邮箱" />
      </n-form-item>
      <n-form-item label="性别">
        <n-radio-group v-model:value="formModel.gender">
          <n-space>
            <n-radio :value="0">男</n-radio>
            <n-radio :value="1">女</n-radio>
          </n-space>
        </n-radio-group>
      </n-form-item>
      <n-form-item label="头像">
        <n-upload
          list-type="image-card"
          :default-upload="false"
          :file-list="fileList"
          :before-upload="beforeUpload"
          :show-preview-button="false"
          :multiple="false"
          :on-update:file-list="handleImgChange"
          class="relative rounded-2"
        >
          <img v-if="imgUrl" :src="imgUrl" class="w-full h-full rounded" alt="哈哈" />
          <n-icon v-show="!imgUrl" :component="Add" class="absolute"></n-icon>
        </n-upload>
      </n-form-item>
      <n-form-item label="描述">
        <n-input v-model:value="formModel.desc" placeholder="请输入描述" />
      </n-form-item>
      <n-form-item label="权限">
        <n-radio-group v-model:value="formModel.isAdmin" disabled>
          <n-space>
            <n-radio :value="true" disabled>管理人员</n-radio>
            <n-radio :value="false" disabled>普通用户</n-radio>
          </n-space>
        </n-radio-group>
      </n-form-item>
      <n-form-item>
        <n-button type="info" class="rounded-2" @click="onSubmit" secondary>提交</n-button>
      </n-form-item>
    </n-form>
  </NCard>
</template>
